﻿using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace TrayAnimation
{
    public partial class TrayForm : Form
    {
        [DllImport("shell32.dll")]
        static extern IntPtr ExtractIcon(IntPtr hInst, string lpszExeFileName, int nIconIndex);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern bool DestroyIcon(IntPtr handle);

        private NotifyIcon trayIcon;
        private ContextMenuStrip trayMenu;
        private System.Windows.Forms.Timer animationTimer;
        private int currentIconIndex = 0;

        public TrayForm()
        {
            InitializeTray();
            InitializeAnimation();
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = false;
        }

        private void InitializeTray()
        {
            trayMenu = new ContextMenuStrip();
            trayMenu.Items.Add("退出", null, OnExit);

            trayIcon = new NotifyIcon
            {
                Text = "托盘动画图标",
                ContextMenuStrip = trayMenu,
                Visible = true
            };

            this.Resize += TrayForm_Resize;
        }

        private void InitializeAnimation()
        {
            animationTimer = new System.Windows.Forms.Timer { Interval = 300 };
            animationTimer.Tick += AnimationTimer_Tick;
            animationTimer.Start();
            UpdateIcon();
        }

        private void UpdateIcon()
        {
            IntPtr iconHandle = ExtractIcon(IntPtr.Zero, "shell32.dll", currentIconIndex);
            if (iconHandle != IntPtr.Zero)
            {
                trayIcon.Icon = Icon.FromHandle(iconHandle);
                DestroyIcon(iconHandle);
            }
            currentIconIndex = (currentIconIndex + 1) % 20;
        }

        private void AnimationTimer_Tick(object sender, EventArgs e) => UpdateIcon();

        private void OnExit(object sender, EventArgs e)
        {
            trayIcon.Visible = false;
            Application.Exit();
        }

        private void TrayForm_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == this.WindowState)
                this.Hide();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                trayIcon.Dispose();
                animationTimer.Dispose();
            }
            base.Dispose(disposing);
        }

        //[STAThread]
        //static void Main()
        //{
        //    Application.EnableVisualStyles();
        //    Application.SetCompatibleTextRenderingDefault(false);
        //    Application.Run(new TrayForm());
        //}
    }
}